package com.zhao.fishingguideserver.mapper;

import com.zhao.fishingguideserver.POJO.Order;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * 订单数据访问接口
 */
@Mapper
public interface OrderMapper {
    
    /**
     * 创建订单
     */
    @Insert("insert into orders(code, detail, product_id, buyer_id, buyer_name, buyer_phone, buyer_address, " +
            "seller_id, quantity, buy_price, total_amount, status, create_time) " +
            "values(#{code}, #{detail}, #{productId}, #{buyerId}, #{buyerName}, #{buyerPhone}, #{buyerAddress}, " +
            "#{sellerId}, #{quantity}, #{buyPrice}, #{totalAmount}, #{status}, now())")
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    int insert(Order order);
    
    /**
     * 更新订单状态
     */
    @Update("update orders set status = #{status}, update_time = now() where id = #{id}")
    int updateStatus(@Param("id") Integer id, @Param("status") String status);
    
    /**
     * 更新订单信息
     */
    @Update("<script>" +
            "update orders set " +
            "<if test='buyerName != null'>buyer_name = #{buyerName},</if>" +
            "<if test='buyerPhone != null'>buyer_phone = #{buyerPhone},</if>" +
            "<if test='buyerAddress != null'>buyer_address = #{buyerAddress},</if>" +
            "<if test='status != null'>status = #{status},</if>" +
            "update_time = now() " +
            "where id = #{id}" +
            "</script>")
    int updateOrder(Order order);
    
    /**
     * 查询所有订单（管理员用）
     */
    @Select("select o.id, o.code, o.detail, o.product_id as productId, o.buyer_id as buyerId, " +
            "o.buyer_name as buyerName, o.buyer_phone as buyerPhone, o.buyer_address as buyerAddress, " +
            "o.seller_id as sellerId, o.quantity, o.buy_price as buyPrice, o.total_amount as totalAmount, " +
            "o.status, o.trade_time as tradeTime, o.create_time as createTime, o.update_time as updateTime, " +
            "p.product_name as productName, p.cover_list as coverList, p.old_level as oldLevel, p.price, " +
            "u.username as sellerName, u.nick_name as sellerPhone " +
            "from orders o " +
            "left join product p on o.product_id = p.product_id " +
            "left join users u on o.seller_id = u.user_id " +
            "order by o.create_time desc")
    List<Order> selectAll();
    
    /**
     * 统计订单数量（管理端，带状态筛选）
     */
    @Select("<script>" +
            "SELECT COUNT(1) FROM orders " +
            "<where>" +
            "<if test='status != null and status != \"\"'>" +
            "AND status = #{status}" +
            "</if>" +
            "</where>" +
            "</script>")
    int countOrders(@Param("status") String status);
    
    /**
     * 分页查询订单（管理端，带状态筛选与创建时间倒序）
     */
    @Select("<script>" +
            "select o.id, o.code, o.detail, o.product_id as productId, o.buyer_id as buyerId, " +
            "o.buyer_name as buyerName, o.buyer_phone as buyerPhone, o.buyer_address as buyerAddress, " +
            "o.seller_id as sellerId, o.quantity, o.buy_price as buyPrice, o.total_amount as totalAmount, " +
            "o.status, o.trade_time as tradeTime, o.create_time as createTime, o.update_time as updateTime, " +
            "p.product_name as productName, p.cover_list as coverList, p.old_level as oldLevel, p.price, " +
            "u.username as sellerName, u.nick_name as sellerPhone " +
            "from orders o " +
            "left join product p on o.product_id = p.product_id " +
            "left join users u on o.seller_id = u.user_id " +
            "<where>" +
            "<if test='status != null and status != \"\"'> AND o.status = #{status} </if>" +
            "</where>" +
            "order by o.create_time desc " +
            "limit #{offset}, #{limit}" +
            "</script>")
    List<Order> selectOrdersPaged(@Param("status") String status,
                                  @Param("offset") Integer offset,
                                  @Param("limit") Integer limit);

    /**
     * 根据订单ID查询订单详情
     */
    @Select("select o.id, o.code, o.detail, o.product_id as productId, o.buyer_id as buyerId, " +
            "o.buyer_name as buyerName, o.buyer_phone as buyerPhone, o.buyer_address as buyerAddress, " +
            "o.seller_id as sellerId, o.quantity, o.buy_price as buyPrice, o.total_amount as totalAmount, " +
            "o.status, o.trade_time as tradeTime, o.create_time as createTime, o.update_time as updateTime, " +
            "p.product_name as productName, p.cover_list as coverList, p.old_level as oldLevel, p.price, " +
            "u.username as sellerName, u.nick_name as sellerPhone " +
            "from orders o " +
            "left join product p on o.product_id = p.product_id " +
            "left join users u on o.seller_id = u.user_id " +
            "where o.id = #{id}")
    Order selectById(@Param("id") Integer id);
    
    /**
     * 根据订单号查询订单
     */
    @Select("select o.id, o.code, o.detail, o.product_id as productId, o.buyer_id as buyerId, " +
            "o.buyer_name as buyerName, o.buyer_phone as buyerPhone, o.buyer_address as buyerAddress, " +
            "o.seller_id as sellerId, o.quantity, o.buy_price as buyPrice, o.total_amount as totalAmount, " +
            "o.status, o.trade_time as tradeTime, o.create_time as createTime, o.update_time as updateTime, " +
            "p.product_name as productName, p.cover_list as coverList, p.old_level as oldLevel, p.price, " +
            "u.username as sellerName, u.nick_name as sellerPhone " +
            "from orders o " +
            "left join product p on o.product_id = p.product_id " +
            "left join users u on o.seller_id = u.user_id " +
            "where o.code = #{code}")
    Order selectByCode(@Param("code") String code);
    
    /**
     * 查询买家的订单列表
     */
    @Select("select o.id, o.code, o.detail, o.product_id as productId, o.buyer_id as buyerId, " +
            "o.buyer_name as buyerName, o.buyer_phone as buyerPhone, o.buyer_address as buyerAddress, " +
            "o.seller_id as sellerId, o.quantity, o.buy_price as buyPrice, o.total_amount as totalAmount, " +
            "o.status, o.trade_time as tradeTime, o.create_time as createTime, o.update_time as updateTime, " +
            "p.product_name as productName, p.cover_list as coverList, p.old_level as oldLevel, p.price, " +
            "u.username as sellerName, u.nick_name as sellerPhone " +
            "from orders o " +
            "left join product p on o.product_id = p.product_id " +
            "left join users u on o.seller_id = u.user_id " +
            "where o.buyer_id = #{buyerId} " +
            "order by o.create_time desc")
    List<Order> selectByBuyerId(@Param("buyerId") Integer buyerId);
    
    /**
     * 查询卖家的订单列表
     */
    @Select("select o.id, o.code, o.detail, o.product_id as productId, o.buyer_id as buyerId, " +
            "o.buyer_name as buyerName, o.buyer_phone as buyerPhone, o.buyer_address as buyerAddress, " +
            "o.seller_id as sellerId, o.quantity, o.buy_price as buyPrice, o.total_amount as totalAmount, " +
            "o.status, o.trade_time as tradeTime, o.create_time as createTime, o.update_time as updateTime, " +
            "p.product_name as productName, p.cover_list as coverList, p.old_level as oldLevel, p.price, " +
            "u.username as buyerName, u.nick_name as buyerPhone " +
            "from orders o " +
            "left join product p on o.product_id = p.product_id " +
            "left join users u on o.buyer_id = u.user_id " +
            "where o.seller_id = #{sellerId} " +
            "order by o.create_time desc")
    List<Order> selectBySellerId(@Param("sellerId") Integer sellerId);
    
    /**
     * 根据状态查询订单
     */
    @Select("select o.id, o.code, o.detail, o.product_id as productId, o.buyer_id as buyerId, " +
            "o.buyer_name as buyerName, o.buyer_phone as buyerPhone, o.buyer_address as buyerAddress, " +
            "o.seller_id as sellerId, o.quantity, o.buy_price as buyPrice, o.total_amount as totalAmount, " +
            "o.status, o.trade_time as tradeTime, o.create_time as createTime, o.update_time as updateTime, " +
            "p.product_name as productName, p.cover_list as coverList, p.old_level as oldLevel, p.price, " +
            "u1.username as sellerName, u1.nick_name as sellerPhone " +
            "from orders o " +
            "left join product p on o.product_id = p.product_id " +
            "left join users u1 on o.seller_id = u1.user_id " +
            "where o.status = #{status} " +
            "order by o.create_time desc")
    List<Order> selectByStatus(@Param("status") String status);
    
    /**
     * 取消订单
     */
    @Update("update orders set status = 'cancelled', update_time = now() where id = #{id}")
    int cancelOrder(@Param("id") Integer id);
    
    /**
     * 删除订单（仅管理员）
     */
    @Delete("delete from orders where id = #{id}")
    int deleteOrder(@Param("id") Integer id);
}